<?php
/**
 * WP_WXTPP_Controller class, used to provide an WXTPP endpoint.
 *
 * @link       https://git.oschina.net/wostech/wp-wxtpp
 * @since      1.0.0
 *
 * @package    WP_WXTPP
 * @subpackage WP_WXTPP/includes
 */

/**
 * WXTPP endpoint controller.
 *
 * Registers the REST API route and delivers the response data.
 * The output format (XML or JSON) is handled by the REST API.
 *
 * @since      1.0.0
 */
class WP_WXTPP_Controller {
	/**
	 * Register the WXTPP REST API route.
	 *
	 * @since 1.0.0
	 */
	public function register_routes() {
		register_rest_route( 'wxtpp/1.0', '/tpp-notify', array(
			array(
				'methods'  => WP_REST_Server::ALLMETHODS,
				'callback' => array( $this, 'tpp_notify' ),
			),
		) );
                register_rest_route( 'wxtpp/1.0', '/gh-notify/(?P<appId>[\w-]+)', array(
			array(
				'methods'         => WP_REST_Server::ALLMETHODS,
				'callback'        => array( $this, 'gh_notify' ),				
			),
		) );
	}

	/**
	 * WeiXin TPP notify URL callback.
	 *
	 *
	 * @since 1.0.0
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_Error|array WXTPP response data or WP_Error on failure.
	 */
	public function tpp_notify( $request ) {
            require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wxtpp.php'; 
            $wxtpp = WXTPP::get_instance();
            return $wxtpp->process( $request );            
	}
        
        /**
	 * WeiXin GH notify URL callback.
	 *
	 *
	 * @since 1.0.0
	 *
	 * @param WP_REST_Request $request Full data about the request.
	 * @return WP_Error|array WXTPP response data or WP_Error on failure.
	 */
	public function gh_notify( $request ) {            
            require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wxtpp-gh.php'; 
            $wxtpp_gh = new WXTPP_GH( $request[ 'appId' ] );
            return $wxtpp_gh->process( $request ); 
	}
}
